<?php

namespace app\h5\v1\controller;

use app\common\ApiBase;
use app\model\Banner;
use support\Redis;
use support\Request;
use support\Response;

class Audio extends ApiBase
{
    const TOKEN_KEY = '03e3e127cdc37c5a';
    const REDIS_KEY = 'app:audio:checkqsenckey:';

    //获取音频文件
    //https://api.OwenWeb.com/h5/audio/get?id=1&time=123&audio_token=123
    //token=md5(秘钥+时间戳) 32位小写
    public function get(Request $request): Response
    {
        $id = $request->get('id', 0);
        if (!$id) return $this->apiFailed('音频id参数错误');
        $id   = (int)$id;
        $time = $request->get('time', 0);
        if (!$time) return $this->apiFailed('音频时间参数错误');
        //请求时间差是否合理值
        if (abs(time() - $time) > config('app.api_timeout')) {
            return $this->apiFailed('音频时间超时');
        }

        $token = $request->get('audio_token', 0);
        if (!$token) return $this->apiFailed('音频token参数错误');
        //校验token,md5(秘钥+时间戳) 小写
        $localToken = md5(config('app.sign_salt') . $time);
        if ($localToken != $token) return $this->apiFailed('音频token错误');
        //验证成功生成新的token
        $newToken = md5(self::TOKEN_KEY . $time);
        //写入把时间redis
        Redis::set(self::REDIS_KEY . $newToken, $time, 'EX', config('app.api_timeout'), 1);
        $where[] = ['id', '=', $id];
        $url1    = Banner::getField($where, 'url');
        if (!$url1) return $this->apiFailed('文件不存在');
        $url    = getBeforeString($url1, '/play.m3u8');
        $ossUrl = OSS_URL . $url . '/';

        //读取OSS文件
        $file = OSS_URL . $url1;
        //文件内容加入数组
        $fileContent = @file($file);
        $newContent  = '';
        //遍历文件的每一行
        foreach ($fileContent as $value) {
            //文件该行是否存在这个字符,有这替换内容
            if (strpos($value, 'api.OwenWeb.com/') !== false) {
                $siteUrl = env('WWW_SITE', 'api.OwenWeb.com');
                $value   = str_replace('api.OwenWeb.com/', $siteUrl . "/h5/audio/checkqsenckey?qsenckey_token=$newToken", $value);
            }
            //文件该行是否存在这个字符,有这拼接内容
            if (strpos($value, '.ts') !== false) {
                $value = $ossUrl . $value;
            }
            $newContent .= $value;
        }

        //写入文件
        $fileName = time() . '.m3u8';
        // ./1656554350.m3u8
        $file = "./$fileName";
        //打开文件
        $handle = fopen($file, 'w');
        //写入内容
        fwrite($handle, $newContent);
        //将文件转字符串
        $content = file_get_contents($file);
        //删除临时文件
        unlink($file);

        //输出浏览器
        $response = new Response();
        return $response
            ->withHeader('Content-Type', 'application/vnd.apple.mpegurl')
            ->withHeader('Content-Disposition', 'attachment; filename="' . $fileName . '"')
            ->withHeader('Accept-Ranges', 'bytes')
            ->withBody($content);
    }

    //获取音频key文件
    public function checkqsenckey(Request $request): Response
    {
        $token = $request->get('qsenckey_token', 0);
        if (!$token) return $this->apiFailed('qsenckey_token参数错误');

        $time = Redis::get(self::REDIS_KEY . $token);
        if (!$time) return $this->apiFailed('qsenckey_time错误');

        //请求时间差是否合理值
        if (abs(time() - $time) > config('app.api_timeout')) {
            return $this->apiFailed('qsenckey时间超时');
        }

        //验证token
        if (md5(self::TOKEN_KEY . $time) != $token) return $this->apiFailed('qsenckey_token错误');

        return redirect(WEB_URL . "/qsenc.key");
    }
}
